package com.yiphonenum.phonenumberapplication;

import android.app.ProgressDialog;
import android.content.ContentProviderOperation;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;


public class MainActivity extends AppCompatActivity {

    static final int PICK_CITY = 0;

    private String carrier;
    private EditText etCity;
    TextView lblAbout;

    RadioGroup ragSelectCarrier;
    private EditText etNum;
    private EditText etGroup;

    private long currentBackPressedTime = 0;
    String group_title;
    // 授权请求码
    static final int LICENSED = 0;

    PhoneMake phone_make;

    AsyncPhoneMake asyncPhoneMake;

    // 备份-恢复
    FileOutputStream mFileOutputStream = null;
    ArrayList<String> vCard;
    Cursor cursor;

    // 1-创建
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etCity = (EditText) findViewById(R.id.etCity);
        etCity.setText("北京");
        carrier = "移动";

        etGroup = (EditText) findViewById(R.id.etGroup);
        // 显示关于
        lblAbout = (TextView) findViewById(R.id.lblAbout);
        lblAbout.setText("千易丐帮开发官方淘宝店（点我）");

        phone_make = new PhoneMake(getApplication());

        ragSelectCarrier = (RadioGroup) findViewById(R.id.ragSelectCarrier);
        ragSelectCarrier.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                // 运营商选择
                RadioButton radioButton = (RadioButton) findViewById(checkedId);
                if (radioButton != null) {
                    carrier = radioButton.getText().toString();
                    // Toast.makeText(getApplication(), carrier, Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(getApplication(), "null", Toast.LENGTH_SHORT).show();
            }
        });

        // 生成号码数量
        etNum = (EditText) findViewById(R.id.etNum);
        // 数据文件
        //SugarContext.init(this);
        AssetDatabaseOpenHelper helper = new AssetDatabaseOpenHelper(getApplication());
        helper.openDatabase();

        // 认证
        if (check_license()) {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, AuthActivity.class);
            startActivityForResult(intent, LICENSED);
        }
        //
    }

    // 2-后退键
    @Override
    public void onBackPressed() {

        if (System.currentTimeMillis() - currentBackPressedTime > 3000) {
            currentBackPressedTime = System.currentTimeMillis();
            Toast.makeText(getApplication(), "再按一次则退出", Toast.LENGTH_SHORT).show();
        } else {
            finish();
        }
    }

    // 3-选择城市返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 得到新Activity 关闭后返回的数据
        if (requestCode == PICK_CITY) {
            if (resultCode == RESULT_OK) {
                String result = data.getExtras().getString("city");
                etCity.setText(result);
            }
        }
        if (requestCode == LICENSED) {
            if (resultCode != RESULT_OK)
                MainActivity.this.finish();
        }
        //
    }

    // 4-活动销毁
    @Override
    public void onDestroy() {
        //SugarContext.terminate();
        super.onDestroy();
    }

    // 5-选择城市按钮
    public void btnCitySelectClick(View view) {
        startActivityForResult(new Intent(MainActivity.this, CitySelectActivity.class), PICK_CITY);
    }

    // 6-线程： 生成号码
    final Handler handler_make = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    Runnable runnable_make = new Runnable() {
        @Override
        public void run() {
            String city = etCity.getText().toString();
            int num = Integer.parseInt(etNum.getText().toString());
            phone_make.makePhone(city, carrier, num);
        }
    };

    // 7-按钮：生成号码
    public void btnMakeClick(View view) {
        // 创建线程
        handler_make.post(runnable_make);

        // 分组名称
        String group_prefix = etCity.getText().toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd_HHmmss", Locale.CHINA);
        String t = sdf.format(new Date());

        group_title = group_prefix + t;
        etGroup.setText(group_title);
    }

    // 8-按钮：导入
    public void btnImport(View view) {
        new AsyncPhoneMake().execute();
/*        asyncPhoneMake = new AsyncPhoneMake();
        asyncPhoneMake.execute();*/
    }

    // 9-异步类： 生成号码
    private class AsyncPhoneMake extends AsyncTask<String, Integer, String> {
        ProgressDialog pd;
        String group_prefix;
        private int idx_current = 0;
        String _id;

        public AsyncPhoneMake() {
            pd = new ProgressDialog(MainActivity.this);
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pd.setCancelable(true);
            pd.setTitle("导入通讯录");

            pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    cancel(true);
                }
            });

            group_prefix = etCity.getText().toString();
        }

        @Override
        protected void onPreExecute() {
            pd.show();

        }

        @Override
        protected String doInBackground(String... strings) {

            ArrayList<String> phones_result = phone_make.getResult();
            if (phones_result.size() == 0) return null;

            // 创建一个分组
            if (!createGroup(group_title)) {
                Toast.makeText(getApplication(), "创建分组失败", Toast.LENGTH_LONG).show();
                return null;
            }

            // 添加联系人
            ArrayList<ContentProviderOperation> ops = new ArrayList<>();
            String DisplayName;
            String MobileNumber;

            pd.setMax(phones_result.size());

            for (int i = 0; i < phones_result.size(); i++) {
                // 退出写入联系人
                if (isCancelled()) {
                    Toast.makeText(getApplication(), "已写入记录" + Integer.toString(i), Toast.LENGTH_LONG).show();
                    break;
                }

                publishProgress(i);

                DisplayName = group_prefix + "_" + String.format(Locale.CHINESE, "%04d", idx_current);
                MobileNumber = phones_result.get(i);

                ops.clear();

                ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "account_name")
                        .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "account_type").build());

                // 姓名
                ops.add(ContentProviderOperation.newInsert(
                        ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                        .withValue(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        .withValue(
                                ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                DisplayName).build());
                // 电话
                ops.add(ContentProviderOperation.newInsert(
                        ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                        .withValue(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
                        .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                        .build());
                // 分组
                ops.add(ContentProviderOperation.newInsert(
                        ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                        .withValue(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, _id)
                        .build());
                // 写入
                try {
                    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                    idx_current++;
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getApplication(), "例外: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            phone_make.clearResult();
            pd.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            pd.incrementProgressBy(1);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            Toast.makeText(getApplication(), "写入通讯薄取消", Toast.LENGTH_SHORT).show();
        }

        // 创建联系人分组
        private boolean createGroup(String title) {
            boolean result;
            ArrayList<ContentProviderOperation> ops = new ArrayList<>();
            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Groups.CONTENT_URI)
                    .withValue(ContactsContract.Groups.TITLE, title).build());
            try {
                getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                result = true;

                // 取插入的分组ID
                final String[] GROUP_PROJECTION = new String[]{
                        ContactsContract.Groups._ID,
                        ContactsContract.Groups.TITLE,
                };

                Cursor c = getContentResolver().query(
                        ContactsContract.Groups.CONTENT_SUMMARY_URI,
                        GROUP_PROJECTION,
                        ContactsContract.Groups.TITLE + "='" + title + "'",
                        null,
                        null);
                c.moveToFirst();
                final int IDX_ID = c.getColumnIndex(ContactsContract.Groups._ID);

                _id = c.getString(IDX_ID);

            } catch (Exception e) {
                Log.e("Error", e.toString());
                result = false;
            }
            return result;
        }
        // end: private class
    }


    //  检查注册情况
    private boolean check_license() {
        // 读取内部保存数据
        SharedPreferences preferences = getSharedPreferences("Profile", MODE_PRIVATE);
        if (preferences != null) {
            boolean licensed = preferences.getBoolean("licensed", false);
            return licensed;
        } else {
            return false;
        }
    }


    // 打开淘宝店铺网页
    public void openTaobao(View view) {
        String url = "https://shop163488616.taobao.com/";
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    // 备份通讯录
    public void btnBackup(View view) {
        new AsyncTaskBackup().execute();
    }


    // 恢复备份
    public void btnRestore(View view) {
        Intent intent = new Intent(MainActivity.this, BackupFileListActivity.class);
        startActivity(intent);
    }

    //
    private void getCursor(Cursor cursor) {
        //cursor.moveToFirst();
        String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
        AssetFileDescriptor fd;
        try {
            fd = getContentResolver().openAssetFileDescriptor(uri, "r");
            FileInputStream fis = fd.createInputStream();
            byte[] buf = new byte[(int) fd.getDeclaredLength()];
            fis.read(buf);
            String vcardstring = new String(buf);
            vCard.add(vcardstring);


            mFileOutputStream.write(vcardstring.getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private class AsyncTaskBackup extends AsyncTask<String, Integer, String> {
        ProgressDialog pd;
        boolean blContactsIsEmpty = false;

        public AsyncTaskBackup() {
            pd = new ProgressDialog(MainActivity.this);
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pd.setCancelable(true);
            pd.setTitle("备份通讯录");
            pd.setOnCancelListener(new ProgressDialog.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    cancel(true);
                }
            });
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd.show();
        }

        @Override
        protected String doInBackground(String... strings) {

            String storage_path = Environment.getExternalStorageDirectory().toString() + "/";

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmm", Locale.CHINA);
            String vfile = "q_backup_" + sdf.format(new Date()) + ".vcf";

            String path = storage_path + vfile;
            File f = new File(path);

            vCard = new ArrayList<>();
            cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, null, null, null);

            if (cursor != null && cursor.getCount() > 0) {
                pd.setMax(cursor.getCount());
                // 有记录才生成文件
                try {
                    if (!f.exists())
                        if (f.createNewFile())
                            mFileOutputStream = new FileOutputStream(path, false);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }

                cursor.moveToFirst();
                for (int i = 0; i < cursor.getCount(); i++) {
                    if (isCancelled())
                        break;

                    getCursor(cursor);
                    cursor.moveToNext();
                    // 更新进度条
                    publishProgress(i);
                }

                try {
                    mFileOutputStream.flush();
                    mFileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else {
                blContactsIsEmpty = true;
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (blContactsIsEmpty)
                Toast.makeText(getApplication(), "无联系人可以备份", Toast.LENGTH_SHORT).show();
            pd.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            pd.incrementProgressBy(1);
        }
    }

    // end
}
